package com.ysy.logistics.controller.common;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.ysy.common.resp.ResultData;
import com.ysy.common.resp.ReturnCodeEnum;
import com.ysy.logistics.entities.supplier.SupGoods;
import com.ysy.logistics.entities.system.SysUser;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.supplier.SupGoodsService;
import com.ysy.logistics.service.system.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/23 1:53
 **/
@Slf4j
@RestController
@RequestMapping(value = "/file",name = "文件")
@Tag(name = "文件管理",description = "文件上传下载")
@CrossOrigin(origins = "*", maxAge = 3600)
public class FileManagerController {

    @Value("${custom.file.save_path:/home/archives}")
    private String savePath;

    /**
     * 头像默认路径
     */
    private static final String DEFAULT_AVATAR_PATH = File.separator + "avatar" ;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SupGoodsService supGoodsService;

    @RequestMapping("/uploadAvatar")
    @Operation(summary = "上传头像",description = "上传头像")
    @OperateLog("上传头像")
    public ResultData uploadAvatar(@RequestParam("file") MultipartFile file){
        //获取登录信息
        if (!StpUtil.isLogin()) {
            return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
        }
        if (file.isEmpty()) {
            return ResultData.fail("上传文件不能为空");
        }
        //文件类型
        String contentType = file.getContentType();
        if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
            return ResultData.fail("上传文件格式不正确");
        }
        //生成文件名
        String fileName = StpUtil.getLoginId() + "." + file.getOriginalFilename().split("\\.")[1];
        //保存文件
        try {
            Path dir = Paths.get(savePath+ DEFAULT_AVATAR_PATH);
            Files.createDirectories(dir);
            file.transferTo(dir.resolve(fileName));
            //更新头像信息
            SysUser sysUser = new SysUser();
            sysUser.setId(StpUtil.getLoginId().toString());
            sysUser.setAvatar(DEFAULT_AVATAR_PATH + File.separator + fileName);
            sysUserService.updateById(sysUser);
            return ResultData.success("");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping("/getAvatar")
    @Operation(summary = "下载文件",description = "根据文件存储真实名称下载")
    public ResponseEntity<byte[]> downloadByName(){
        //获取登录信息
        if (!StpUtil.isLogin()) {
            return  ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        String storedFileName = savePath + sysUserService.getById(StpUtil.getLoginId().toString()).getAvatar();
        if (StringUtils.isEmpty(storedFileName)){
            storedFileName = savePath + DEFAULT_AVATAR_PATH + File.separator+"default.png";

        }
        File file = new File(storedFileName);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDisposition(ContentDisposition.
                builder("inline").
                filename(file.getName(), StandardCharsets.UTF_8)
                .build());
        httpHeaders.setContentType(MediaType.parseMediaType("application/octet-stream"));
        httpHeaders.setContentLength(file.length());

        try {
            return ResponseEntity.ok().headers(httpHeaders).body(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            log.error("下载失败", e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }


    @GetMapping("/getFileByGoodsId/{id}")
    @Operation(summary = "下载文件",description = "根据文件存储真实名称下载")
    public ResponseEntity<byte[]> getFileByPath(@PathVariable("id") String id){
        if (StringUtils.isEmpty(id)){
            return  ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        SupGoods byId = supGoodsService.getById(id);
        String url = byId.getPic();
        String storedFileName = savePath +url;
        File file = new File(storedFileName);
        if (!file.exists()){
            return  ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDisposition(ContentDisposition.
                builder("inline").
                filename(file.getName(), StandardCharsets.UTF_8)
                .build());
        httpHeaders.setContentType(MediaType.parseMediaType("application/octet-stream"));
        httpHeaders.setContentLength(file.length());

        try {
            return ResponseEntity.ok().headers(httpHeaders).body(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            log.error("下载失败", e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

}
